import { login, getLogout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import router from "@/router";
import { Routes, AllAsyncRoutes, AnyRoute } from "@/router/routes";
import cloneDeep from "lodash/cloneDeep";
const getDefaultState = () => {
  return {
    name:  "",
    avatar: "",
    token: localStorage.getItem("token_key") || "",
    buttons: [],
    routes: [],
    roles: [],
    menuRoutes: [],
    userInfo: {}
  };
};

// 用户登录携带的信息，去过滤出用户权限自己能看到的异步路由
const filterAsyncRoutes = (AllAsyncRoutes, userRoutesName) => {
  return AllAsyncRoutes.filter((item) => {
    // indexOf--找到符合条件元素的索引位置,找不到返回-1
    // 筛选一级路由名字
    if (userRoutesName.indexOf(item.name) !== -1) {
      // 筛选二级路由
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, userRoutesName);
      }
      return true;
    }
  });
};

// 动态添加到路由器中，因为此时路由器中只有静态路由；
// 而侧边栏的显示是由遍历动态路由生成的
const addUserRoutes = (routes) => {
  // 使用路由器的api去动态添加,每一次只能添加一个
  // 遍历添加所有
  // routes.forEach(item => {
  router.addRoutes(routes);
  // })
};

const state = getDefaultState();
// token:localStorage.getItem("token_key") ||''

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    debugger
    state.name = name;
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons;
  },
  SET_ROUTES(state, routes) {
    state.routes = routes;
  },
  SET_ROLES(state, roles) {
    state.roles = roles;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_MENUROUTES: (state, menuRoutes) => {
    state.menuRoutes = menuRoutes;
  },
  SET_USERINFO(state, userInfo) {
    state.userInfo = userInfo
  }
};

const actions = {
  async login({ commit }, data) {
    try {
      const result = await login(data);
      localStorage.setItem("token_key", result.data.token);
      setToken();
      commit("SET_TOKEN", result.data.token);
    } catch (error) {
      return Promise.reject(error);
    }
  },

  async getInfo({ commit }) {
    try {
      const result = await getInfo();
      localStorage.setItem("USERINFO", result.data.name)
      commit("SET_NAME", result.data.name);
      commit("SET_AVATAR", result.data.avatar);
      // commit("SET_BUTTONS", result.data.buttons);
      commit("SET_ROUTES", result.data.routes);
      commit("SET_ROLES", result.data.roles);
      commit("SET_USERINFO", result.data)
      console.log(result.data.buttons)
      let userAsyncRoutes = filterAsyncRoutes(
        cloneDeep(AllAsyncRoutes),
        result.data.routes
      );
      addUserRoutes(userAsyncRoutes.concat(AnyRoute));
      let menuRoutes = Routes.concat(userAsyncRoutes, AnyRoute);
      commit("SET_MENUROUTES", menuRoutes);
      return "ok";
    } catch (error) {
      return Promise.reject(error);
    }
  },
  async logout({ commit }) {
    try {
      await getLogout();
      localStorage.removeItem("token_key");
      resetRouter();
      commit("RESET_STATE");
      return "ok";
    } catch (error) {
      return Promise.reject(error);
    }
  },
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
